<?php

namespace app\third\controller;

use think\facade\Db;

class Controller extends \app\BaseController
{
    protected $agent = null;

    protected function initialize()
    {
        $data = input('post.');
        if (empty($data['app_key'])) {
            $this->showError('缺少参数 app_key', CODE_MISS_PARAM);
        }
        if (empty($data['sign'])) {
            $this->showError('缺少参数 sign', CODE_MISS_PARAM);
        }
        if (empty($data['timestamp'])) {
            $this->showError('缺少参数 timestamp', CODE_MISS_PARAM);
        }

        $agent = Db::name('agent')
            ->where('app_key', $data['app_key'])
            ->where('is_deleted', 0)
            ->find();
        if (empty($agent)) {
            $this->showError('账号不存在', CODE_ACCOUNT_NOT_FOUND);
        }
        unset($agent['password']);
        if ($agent['status'] != 1) {
            $this->showError('账号被禁用', CODE_ACCOUNT_FORBIDDEN);
        }

        // IP白名单
        $ip = $this->request->ip();
        if (empty($agent['ip_address'])) {
            $this->showError('IP白名单尚未配置，请先联系管理员进行配置', CODE_IP_ERROR);
        }
        if (!empty($agent['ip_address'])) {
            $ipArr = explode(',', $agent['ip_address']);
            if (!in_array($ip, $ipArr)) {
                $this->showError('IP【'.$ip.'】不在白名单内', CODE_IP_ERROR);
            }
        }

        if ($data['sign'] != getSign($data, $agent['app_secret'])) {
            $this->showError('签名错误', CODE_SIGN_ERROR);
        }
        $time = abs(time() - $data['timestamp']);
        if ($time > 180) {
            $this->showError('请求已过期: '.date('Y-m-d H:i:s', $data['timestamp']), CODE_TIMESTAMP_TIMEOUT);
        }

        $this->agent = $agent;
    }

    private function showError($message, $code)
    {
        exit(json_encode([
            'code' => $code,
            'message' => $message,
            'data' => [],
        ], JSON_UNESCAPED_UNICODE));
    }
}
